import {Component, OnInit, ViewChild} from '@angular/core';
import {FetchService} from "../../../../core/net/fetch.service";
import {DataReportService} from "../../data-report.service";
import * as _ from 'lodash';
import {NzFormatEmitEvent, NzTreeComponent} from "ng-zorro-antd";
import * as moment from 'moment';
import {UtilService} from "../../../../core/util/util.service";
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

@Component({
    selector: 'app-wt-monthly',
    templateUrl: './wt-monthly.component.html',
    styleUrls: ['./wt-monthly.component.scss', '../water-takes-report.component.scss']
})
export class WtMonthlyComponent implements OnInit {
    @ViewChild('objTreeComponent') objTreeComponent: NzTreeComponent;
    listData = [];
    currentNode: any;  //  默认选中灌区对象
    contentTitle: string;
    today = new Date();
    datePicker: Date = new Date();

    tableData = [];
    basicOpts: any = {
        title: {
            text: "",
            x: "center",
            textStyle: {
                color: "#777",
                fontSize: 16
            }
        },
        color: ['#3398DB', '#ddb00a'],
        grid: {
            top: '10%',
            left: '8%',
            right: '8%',
            bottom: '12%',
            containLabel: true
        },
        tooltip: {
            trigger: "axis"
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: []
        },
        yAxis: {
            type: "value"
        }
    };
    customOpts: any = {};
    modalTitle: string = '水情月报历史数据';
    modalShow: boolean = false;
    progressModalShow: boolean = false;
    progressData = [];
    reportFinished = 0;
    reportUnfinished = 0;
    reportPercentage = 0;

    frId = 32;

    // 引黄灌区
    yearValue = 2020;
    monthPickerValue = new Date().getMonth();
    serverUrl = (window as any).environment.reportUrl;
    iframeSrc: SafeResourceUrl;

    //  非引黄灌区
    isGhMng = false;    //  是否为固海管理处
    radioValue = 'GHYS';
    areaHeadArr = [];
    areaTableData = [];
    reportType: string = '1'; //  上报类型： '1'月度 '2'灌季年度
    monthlyTableData = [];
    yearlyTableData = [];
    monthlyHeadArr = [
        '计划引水量',
        '实际引水量',
        '区间补水量',
        '比计划超节情况',
        '支（斗）口计划配水量',
        '支（斗）口实际配水量',
        '自用水量',
        '干渠退水',
        '渠道利用系数',
        '商品率（%）'
    ];
    monthlyKeyArr = [
        'officeName',
        'planWatDiv',
        'planWatDivTotal',
        'actWatDiv',
        'actWatDivTotal',
        'intWatSup',
        'intWatSupTotal',
        'overWat',
        'overWatPer',
        'overWatTotal',
        'overWatTotalPer',
        'planWatDist',
        'planWatDistTotal',
        'actWatDist',
        'actWatDistTotal',
        'watConsum',
        'watConsumTotal',
        'canDewat',
        'canDewatTotal',
        'useFactor',
        'useFactorTotal',
        'commoRate',
        'commoRateTotal'
    ];
    yearlyKeyArr = [
        'officeName',
        'planWatDiv',
        'actWatDiv',
        'intWatSup',
        'overWat',
        'overWatPer',
        'planWatDist',
        'actWatDist',
        'watConsum',
        'canDewat',
        'useFactor',
        'commoRate'
    ];
    constructor(
        private fetchService: FetchService,
        private dataReportService: DataReportService,
        private util: UtilService,
        private sanitizer: DomSanitizer
    ) {
    }

    ngOnInit() {
        this.fetchService.post<any>('muw/wrsMuwFr/list', {type: "5"}).subscribe(res => {
            console.log(res);
            const topNode = _.find(res, item => {
                return item.pid === 0;
            });
            this.currentNode = [topNode.id];
            this.contentTitle = topNode.name;
            res.forEach(item => {
                item.title = item.name;
                item.key = item.id;
                item.idPath = `${item.path}/${item.id}`;
                item.parentIds = `${item.path.split('/').join()},${item.id}`;
                item.parentId = item.pid;
                item.isLeaf = item.path.split('/').length > 3;
            });
            res.unshift({id: '0', name: '全部', idPath: '/0/'});
            this.dataReportService.flat2Nested<any>(res, {pathProperty: 'idPath', rootId: '0'}).subscribe(resp => {
                console.log(resp.children);
                this.listData = resp.children;
            });

            this.getGridData(topNode.id);
            this.getProgressData();
        });
    }

    getProgressData(): void {
        this.fetchService.get<any>('muw/submit/querySubmitWr').subscribe(res => {
            if (res) {
                const group = _.groupBy(res, 'statu');
                this.reportFinished = group['2'] ? group['2'].length : 0;
                this.reportUnfinished = group['1'] ? group['1'].length : 0;
                this.reportPercentage = res.length === 0 ? 0 : Math.round(this.reportFinished / res.length * 100);
                res.forEach(item => {
                    item['status'] = item.statu === 1 ? '未报送' : '已报送';
                });
                this.progressData = _.sortBy(res, o => {
                    return o.statu;
                });
            }
        });
    }

    openProgressModal(): void {
        this.progressModalShow = true;
    }

    closeProgressModal() {
        this.progressModalShow = false;
    }

    selectedAreaChanged(event: NzFormatEmitEvent): void {
        console.log(event);
        this.currentNode = event.keys;
        const nodeClick = event.node;
        // this.currentNode = event.node.key;
        nodeClick.isSelected = true;
        this.contentTitle = event.nodes[0].title;
        if (this.currentNode[0] !== 33 && this.currentNode[0] !== 34 && this.currentNode[0] !== 35) {
            this.getGridData(this.currentNode[0]);
        }
    }

    getGridData(frId): void {
        this.frId = frId;
        //  引黄灌区
        if (this.frId === 32) {
            this.queryYhgqInfo();
        } else {
            // this.fetchService.post<any>('muw/wrsMuwWrData/list', {frId: frId}).subscribe(res => {
            //     this.tableData = res.wrsMuwWrDatas;
            //     // this.getHistorydata(frId);
            // });
            this.getMngGridData();
        }
    }
    getMngGridData(): void {
        this.fetchService.post<any>('muw/wrsMuwWrData/list', {frId: this.frId}).subscribe(res => {
            if (res && res.wrsMuwWrDatas.length) {
                const group = _.groupBy(res.wrsMuwWrDatas, 'classify');
                // console.log(group);
                this.isGhMng = Object.keys(group).length > 1;
                // const params = this.isGhMng ? this.radioValue : '';
                // this.uploadUrl = `${(window as any).environment.apiBaseUrl}muw/wrsMuwMReport/import?classify=${params}`;
                let listData = [];
                if (this.isGhMng) {
                    listData = group[this.radioValue];
                } else {
                    listData = res.wrsMuwWrDatas;
                }
                // this.resDataCache = res;
                this.areaHeadArr = listData.map(item => {
                    return item.trWrName;
                });
                //  合计
                const valArr0 = [];
                const totalValArr0 = [];
                //  农业
                const valArr = [];
                const totalValArr = [];
                //  工业
                const valArr1 = [];
                const totalValArr1 = [];
                //  生活
                const valArr2 = [];
                const totalValArr2 = [];
                //  生态
                const valArr3 = [];
                const totalValArr3 = [];
                //  区外供水
                const valArr4 = [];
                const totalValArr4 = [];
                listData.forEach(item => {
                    valArr0.push(item.currentTotal);
                    totalValArr0.push(item.total);
                    valArr.push(item.val);
                    totalValArr.push(item.valTotal);
                    valArr1.push(item.val1);
                    totalValArr1.push(item.val1Total);
                    valArr2.push(item.val2);
                    totalValArr2.push(item.val2Total);
                    valArr3.push(item.val3);
                    totalValArr3.push(item.val3Total);
                    valArr4.push(item.val4);
                    totalValArr4.push(item.val4Total);
                });
                const firstRow = {
                    id: 1,
                    name: '本月'
                };
                const secondRow = {
                    id: 2,
                    name: '累计'
                };
                const firstRow1 = {
                    id: 3,
                    name: '本月'
                };
                const secondRow1 = {
                    id: 4,
                    name: '累计'
                };
                const firstRow2 = {
                    id: 5,
                    name: '本月'
                };
                const secondRow2 = {
                    id: 6,
                    name: '累计'
                };
                const firstRow3 = {
                    id: 7,
                    name: '本月'
                };
                const secondRow3 = {
                    id: 8,
                    name: '累计'
                };
                const firstRow4 = {
                    id: 9,
                    name: '本月'
                };
                const secondRow4 = {
                    id: 10,
                    name: '累计'
                };
                const firstRow0 = {
                    id: 11,
                    name: '本月'
                };
                const secondRow0 = {
                    id: 12,
                    name: '累计'
                };
                this.areaHeadArr.forEach((key, idx) => {
                    firstRow0[key] = valArr0[idx];
                    secondRow0[key] = totalValArr0[idx];
                    firstRow[key] = valArr[idx];
                    secondRow[key] = totalValArr[idx];
                    firstRow1[key] = valArr1[idx];
                    secondRow1[key] = totalValArr1[idx];
                    firstRow2[key] = valArr2[idx];
                    secondRow2[key] = totalValArr2[idx];
                    firstRow3[key] = valArr3[idx];
                    secondRow3[key] = totalValArr3[idx];
                    firstRow4[key] = valArr4[idx];
                    secondRow4[key] = totalValArr4[idx];
                });
                this.areaTableData = [firstRow, secondRow, firstRow1, secondRow1, firstRow2, secondRow2, firstRow3, secondRow3, firstRow4, secondRow4];
                this.fetchService.post<any>('muw/wrsMuwMReport/list', {frId: this.frId}).subscribe(r => {
                    if (r) {
                        const tableGroup = _.groupBy(r, 'classify');
                        let tableData = [];
                        if (this.isGhMng) {
                            tableData = tableGroup[this.radioValue];
                        } else {
                            tableData = r;
                        }
                        this.monthlyTableData = tableData;
                        this.yearlyTableData = tableData;
                    }
                });
            }
        });
    }
    queryYhgqInfo(): void {
        const year = this.yearValue;
        let beginMonth;
        let endMonth;
        if (this.monthPickerValue < 12) {
            beginMonth = this.monthPickerValue + 1;
            endMonth = this.monthPickerValue + 1;
        } else if (this.monthPickerValue == 13) {
            beginMonth = 4;
            endMonth = 9;
        } else if (this.monthPickerValue == 14) {
            beginMonth = 10;
            endMonth = 11;
        } else if (this.monthPickerValue == 15) {
            beginMonth = 4;
            endMonth = 11;
        }
        const token = localStorage.token;
        const link = `${this.serverUrl}preview?_u=wrs:水情月报报表.ureport.xml&_t=3,6&year=${year}&beginMonth=${beginMonth}&endMonth=${endMonth}&token=${token}`;
        this.iframeSrc = this.sanitizer.bypassSecurityTrustResourceUrl(link);
    }
    getHistorydata(frId): void {
        const params = {
            frId: frId,
            startDate: moment().subtract(6, 'months').valueOf(),
            endDate: moment().valueOf(),
        };
        this.fetchService.post<any>('muw/wrsMuwWrData/historyDataList', params).subscribe(res => {
            res.forEach(item => {
                item.date = moment(item.time).format("YYYY-MM");
            });
            const xAxisArr = res.map(item => {
                return item.date;
            });
            const seriesData = res.map(results => {
                return this.util.sum(this.util.getItemValues(results.wrsMuwWrDatas, 'val', true));
            });
            this.customOpts = {
                title: {
                    text: `${this.contentTitle}水量历时曲线`
                },
                xAxis: {
                    data: xAxisArr,
                    axisLabel: {
                        interval: 0
                    }
                },
                yAxis: {
                    name: '用水量(亿m³)'
                },
                series: [
                    {
                        name: '用水量',
                        type: 'line',
                        data: seriesData
                    }
                ]
            };
        });
    }

    openDetailModal(): void {
        this.modalShow = true;
    }

    export(): void {

    }

    print(): void {
    }

    onCancel() {
        this.modalShow = false;
    }

    queryInfo(date): void {
        console.log(date);
    }
}
